home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 2246 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.8 KB

  1. Path: mail2news.demon.co.uk!hpl3sn03.cern.ch
  2. From: Dan Pop <danpop@mail.cern.ch>
  3. Newsgroups: comp.lang.c
  4. Subject: Re: quick decision: is n a power of 2?
  5. Date: Sat, 20 Jan 1996 02:25:46 +0100
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <9601200125.AA12574@dxmint.cern.ch>
  8. References: <4dorr8$i58@cloner3.netcom.com> <4dp5dk$t3r@newsbf02.news.aol.com>
  9. X-NNTP-Posting-Host: hpl3sn03.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11. X-Mail2News-Path: dxmint.cern.ch!hpl3sn03.cern.ch
  12.  
  13. babycox@aol.com (BabyCox) writes:
  14.  
  15. >>#define ISPOW2(x) (((x) & 1) ^ 1)
  16. >
  17. >That will not work, it returns the next lowest MULTIPLE of two,
  18.  
  19. Nope, it returns either 0 (for odd numbers) or 1 (for even numbers).
  20.  
  21. >here's what I would do:
  22. >
  23. >Boolean IsPowerOfTwo(long x)
  24.  
  25. There is no Boolean type in C.
  26.  
  27. >{
  28. >  for(short y = 0;y<=31;y++)
  29.        ^^^^^
  30. This is a syntax error in C.
  31.  
  32. >  {
  33. >    if (x = 1) return true;
  34.          ^^^^^
  35. Are you sure that this is what you meant?
  36.  
  37. >    x >>= 1;
  38.  
  39. The result of this expression is implementation-defined if x < 0.
  40.  
  41. >  }
  42. >  return false;
  43. >}
  44.  
  45. C doesn't define the "true" and "false" symbols.  
  46.  
  47. Now let's rewrite the function in proper C and have a look at it:
  48.  
  49. int IsPowerOfTwo(unsigned long x) 
  50. {
  51.   short y;
  52.  
  53.   for (y = 0; y < 31; y++)
  54.   {
  55.      if (x == 1) return 1;
  56.      x >>= 1;
  57.   }
  58.   return 0;
  59. }
  60.  
  61. Unless I'm missing something, this function will return 1 whenever its
  62. argument is non-null and 0 when its argument is 0.  A considerably faster
  63. way to implement it would be:
  64.  
  65. #define IsPowerOfTwo(x) (!!(x))
  66.  
  67. Needless to say, its name is very misleading and it doesn't solve the
  68. original poster's problem :-)
  69.  
  70. Moral: keep untested advice for yourself.  If you can't be bothered to test
  71. them, why should we be bothered to read them?
  72.  
  73. Dan
  74. -- 
  75. Dan Pop
  76. CERN, CN Division
  77. Email: danpop@mail.cern.ch 
  78. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  79.